<template>
   <div class="add-container" >
      <el-form class="add-panel" label-width="130px"
         :rules = "rules"
         :model="tenat"
         ref="tenat"
         >
         <el-form-item prop="salt">
            <div class="panel" style="margin-left:30%">
               <el-row>
                  <el-avatar :src="tenat.salt" shape="square" :size="100" style="margin-left:10px"/>
               </el-row>
               <!-- 文件上传按钮 -->
               <el-row>
                  <el-button style="margin:10px 0" type="success" icon="el-icon-upload" @click="imagecropperShow=true">
                     {{tenat.salt == null ? '上传' : '更新'}}头像
                  </el-button>
               </el-row>
            </div>
         </el-form-item>
         <el-form-item prop="nickName" label="用户名称:">
            <el-input type="text" prefix-icon="el-icon-edit-outline" placeholder="请输入用户名称"
            clearable v-model="tenat.nickName"/>
         </el-form-item>

         <el-form-item prop="username" label="用户账号:">
            <el-input type="text" prefix-icon="el-icon-edit-outline" placeholder="请输入用户账号"
            v-model="tenat.username" :disabled='!flag' onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"/>
         </el-form-item>

         <el-form-item hidden="true" prop="category">
            <el-input v-model="tenat.category" hidden="true"></el-input>
         </el-form-item>

         <el-form-item prop="email" label="邮箱地址:">
            <el-input type="email" prefix-icon="el-icon-edit-outline"
            v-model="tenat.email" placeholder="请输入邮箱地址"></el-input>
         </el-form-item>

         <el-form-item prop="roleId" label="用户角色:">
            <el-select style="width:100%" v-model="tenat.roleId" placeholder="请选择用户角色">
               <el-option
                  v-for="item in roleLists"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
               </el-option>
            </el-select>
         </el-form-item>
         <el-form-item v-if="flag" prop="password" label="登录密码:" >
            <el-input type="password" placeholder="登录密码" prefix-icon="el-icon-edit-outline"
            v-model="tenat.password"/>
         </el-form-item>
         <el-form-item v-if="flag" prop="rePassword" label="确认密码:" >
            <el-input type="password" placeholder="确认密码" prefix-icon="el-icon-edit-outline"
            v-model="tenat.rePassword"/>
         </el-form-item>
         <el-form-item prop="enterpriseName" label="所属企业:" >
            <el-input type="text" placeholder="所属企业" prefix-icon="el-icon-edit-outline"
            v-model="tenat.enterpriseName"/>
         </el-form-item>
         <el-form-item label="用户描述:" >
            <el-input type="textarea" placeholder="请输入内容" prefix-icon="el-icon-edit-outline"
            v-model="tenat.description"/>
         </el-form-item>
         <el-form-item class="add-btn">
            <el-button type="primary" @click="check">提交</el-button>
         </el-form-item>
      </el-form>

      <image-cropper
         v-show="imagecropperShow"
         :width="300"
         :height="300"
         :key="imagecropperKey"
         :url="BASE_API+'/sys/file/uploadImg'"
         field="file"
         @close="close"
         @crop-upload-success="cropSuccess"/>
   </div>
</template>
<script>
import tenatApi from '@/api/tenant'
import card from '@/components/card/card'
import ImageCropper from '@/components/ImageCropper'

const tenantForm={
  nickName:'',
  username:'',
  salt:'',
  email:'',
//   roleName:'租户角色1',
  roleId:'',
  password:'',
  rePassword:'',
  enterpriseName:'',
  description:'',
  category:'2'
}

export default {
   components: { ImageCropper,card },
   // components: { card },
   data() {
      var validUsername = (rule, value, callback) => {
         if(value != '' && value != null) {
            tenatApi.usernameIsExist(value).then(res => {
               if(res.data.exist && value != this.username) {
                  callback(new Error('该用户名已存在，请重新输入'));
               } else {
                  if(value.length <3 || value.length > 15) {
                     callback(new Error('账号不能小于3位且不能大于15位'));
                  }
                  callback()
               }
            })
         }
      }
      var validatePass = (rule, value, callback) => {
        if (value === '' || value == null) {
          callback(new Error('请输入登录密码'));
        } else {
          if(value.length <6 || value.length > 20) {
            callback(new Error('密码不能小于6位且不能大于20位'));
          }
          if (this.tenat.rePassword !== '') {
            this.$refs.tenat.validateField('rePassword');
          }
          callback();
        }
      }
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.tenat.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }
      var checkEmail = (rule, value, callback) => {
         const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
         console.log("email",value);
         if (value != '' && value !=null) {
            if (mailReg.test(value)) {
               callback()
            } else {
               callback(new Error('请输入正确的邮箱格式'))
            }
         } else {
            callback()
         }
      }
      return {
        username: '',
        roleLists:[{
           id:'',
           roleName:''
        }],
        flag: true,
        category: 2,
        tenat: tenantForm,
        //上传弹框组件是否显示
         imagecropperShow: false,
         imagecropperKey: 0,//上传组件key值
         BASE_API: process.env.BASE_API, //获取dev.env.js里面地址
         rules: {
            nickName:[
               { required: true, message: '请输入用户名称', trigger: 'blur' },
            ],
            username:[
               { required: true, message: '请输入用户账号', trigger: 'blur'},
               { validator: validUsername, trigger: 'blur'}
            ],
            roleId:[
               { required: true, message: '请选择用户角色', trigger: 'blur' }
            ],
            email:[
               { required: false, message: '请输入邮箱地址', trigger: 'change' },
               { validator: checkEmail, trigger: 'blur' },
            ],
            department:[
               { required: true, message: '请输入用户企业', trigger: 'blur' }
            ],
            password:[
               { validator: validatePass, trigger: 'blur' },
               { required: true, message: '请输入登录密码', trigger: 'blur' }
            ],
            rePassword:[
               { validator: validatePass2, trigger: 'blur' },
               { required: true, message: '请再次输入密码', trigger: 'blur' }
            ],
            enterpriseName:[
               { required: true, message: '请输入所属企业', trigger: 'blur' }
            ]
         }
      }
   },
   created() {//页面渲染之前执行
      //获取路由id值
      //调用接口得到医院设置信息
      if(this.$route.params && this.$route.params.id) {
         this.flag = false
         const id = this.$route.params.id
         this.getTenant(id)
      } else {
         //表单数据清空
         this.tenat = {}
      }
      //获取下拉框的角色列表
     this.getTenantRoleList()
   },

   methods: {
      async isExist(username) {
         if(username != '' && username != null) {
            await tenatApi.usernameIsExist(username).then(res => {
               return res.data.exist
            })
         }
         return false 
      },
      close() { //关闭上传弹框的方法
         this.imagecropperShow=false
         //上传组件初始化
         this.imagecropperKey = this.imagecropperKey+1
      },
      //上传成功方法
      cropSuccess(data) {
         this.imagecropperShow=false
         //上传之后接口返回图片地址
         // this.avatar = data.imgurl
         this.tenat.salt = data.imgurl
         // this.user.salt = this.avatar
         this.imagecropperKey = this.imagecropperKey+1
      },
     getTenantRoleList() {
       tenatApi.getTenantRoleList(this.category).then(res=>{
            this.roleLists=res.data.roleLists
       })
     },
     async check() {
         this.$refs.tenat.validate(valid => {
            // 如果验证失败，不发送请求
            console.log(valid)
            if (!valid) {
               return false
            }
            this.saveOrUpdate()
         })
      },
      //根据id查询
      getTenant(id) {
         tenatApi.getTenantById(id).then(response => {
            this.username = response.data.userinfo.username
            this.tenat = response.data.userinfo
            this.tenat.rePassword = this.tenat.password
         })
      },
      //添加
      save() {
        this.tenat.category=2
         tenatApi.saveTenat(this.tenat)
            .then(response => {
               //提示
               if(response.success){
                  this.$message({
                     type: 'success',
                     message: '添加成功!'
                  })
               this.$router.push({path:'/tenant/list'})
               }
               //跳转列表页面，使用路由跳转方式实现
            }).catch(err=>{
               this.$message.error('添加失败,请检查输入信息')
            })
      },
      //修改
      update() {
         this.tenat.category=2
         tenatApi.updateTenant(this.tenat)
            .then(response => {
               //提示
               if(response.success){
                  this.$message({
                     type: 'success',
                     message: '修改成功!'
                  })
                  //跳转列表页面，使用路由跳转方式实现
                  this.$router.push({path:'/tenant/list'})
               }
            }).catch(err=>{
               this.$message.error('修改失败,请检查输入信息')
            })
      },
      saveOrUpdate() {
         //判断添加还是修改
         if(!this.tenat.id) { //没有id，做添加
            this.save();
         }else {//修改
            this.update()
         }
      }
   }
}
</script>

<style scoped>
.add-panel{
   background-color: white;
   padding: 20px 25% 20px 25%;
}
.add-btn{
   text-align: center;
}
.add-container .add-panel .el-form-item__label {
   /* font-weight: normal !important; */
   font-size: 15px !important;
   /* font-family: Verdana !important; */
}
</style>
